package com.esd.crm.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.esd.crm.entity.DocInformation;
import com.esd.crm.mapper.DocInformationMapper;
import com.esd.crm.service.DocInformationService;
import com.esd.crm.util.FileUtils;
import com.esd.crm.util.KitService;
import com.esd.vo.ReturnResult;
import com.github.pagehelper.util.StringUtil;

@Service
public class DocInformationServiceImpl implements DocInformationService{
	
	@Autowired
	private DocInformationMapper docInformationMapper;
	

	private static Logger logger = Logger.getLogger(FilegagsServiceImpl.class);
	@Value(value = "${resourceFilePath}")
	private String resourceFilePath; // 超级管理员执行初始化文件时 存放的路径-资源文件保存路径
	@Value(value = "${tempFilePath}")
	private String tempFilePath; // 刚上传文件的缓存目录
	@Value(value = "${fileNameSpliter}")
	private String fileNameSpliter;// 新旧文件名分隔符
	
	
	@Override
	public ReturnResult addFile(DocInformation docInformation, HttpServletRequest request, HttpSession session){
		
		if(StringUtils.isBlank(docInformation.getFileName())){
			System.out.println("没有上传任何文件");
			return ReturnResult.fail("没有上传任何文件");
		}
		
		// 处理上传的文件列表, 将文件移动到资源文件夹中
		//TODO
		String tempFolderPath=(String)session.getAttribute("filepath");
		String resourcesFolderPath=request.getSession().getServletContext().getRealPath(resourceFilePath);
		
		docInformation=moveDocToResourcePathAndSaveFileToDB(tempFolderPath,resourcesFolderPath,docInformation,"1");
		
		if(docInformation==null){
			System.out.println("处理上传文件时发生错误.");
			logger.error("处理上传文件时发生错误.");
			return ReturnResult.fail("操作发生错误, 请联系管理员.");
		}
		
		boolean s=insertSelective(docInformation);
		
		if(!s){
			System.out.println("文件上传失败！");
			return ReturnResult.fail("文件上传失败！");
		}
		
		return ReturnResult.success();
	}



	private DocInformation moveDocToResourcePathAndSaveFileToDB(String tempFolderPath, String resourcesFolderPath,
			DocInformation docInformation, String operatorId) {
		
		String fileName=docInformation.getFileName();
		if(StringUtils.isBlank(fileName)){
			logger.warn("moveFileToResourcePathAndSaveFileToDB(String fileName), fileName is null");
			System.out.println(
					"moveFileToResourcePathAndSaveFileToDB(String fileName), fileName is null");
			return null;
		}
		
		//获取文件的后缀类型
		int a=fileName.lastIndexOf(".");
		String suffix=fileName.substring(a);
		
		//判断fileName存在，判断文件是否能根据路径找到
		String id="";
		String newFileName = "";

		//srcFile是文件的目录+命名
		File srcFile = null;
		if(fileName.indexOf(fileNameSpliter)>0){
			id = fileName.substring(0, fileName.indexOf(fileNameSpliter));
			newFileName = id + suffix;
			
			srcFile=new File(tempFolderPath+fileName);
			System.out.println("tempFolderPath:"+tempFolderPath);
			System.out.println("fileName:"+fileName);
			//判断文件是否存在
			if(!srcFile.exists()){
				logger.warn("srcFile: " + tempFolderPath + File.separator + fileName + " not exists!");
				System.out.println("srcFile: " + tempFolderPath + fileName + " not exists!");
				return null;
			}
		}
		
		//往实体类传信息，要根据这些信息往数据库里添加文件
		docInformation.setId(id);
		docInformation.setFileName(newFileName);
		docInformation.setCreateBy(operatorId);
		docInformation.setUpdateBy(operatorId);
		Date now = new Date();
		docInformation.setCreateTime(now);
		docInformation.setUpdateTime(now);
		docInformation.setFileSuffix(suffix);
		docInformation.setLength(srcFile.length());
		docInformation.setFile(FileUtils.getByteFromFile(srcFile));
		
	    return docInformation;
	}


	@Override
	public boolean insertSelective(DocInformation docInformation) {
		
		if (docInformation == null) {
			logger.info("object is null");
			return false;
		}
		if (StringUtils.isBlank(docInformation.getId())) {
			docInformation.setId(KitService.getUUID());
		}
		Date now = new Date();
		if (docInformation.getCreateTime() == null) {
			docInformation.setCreateTime(now);
		}
		if (docInformation.getUpdateTime() == null) {
			docInformation.setUpdateTime(now);
		}
		
		
		
		boolean flag = docInformationMapper.insertSelective(docInformation);
		System.out.println("文件存入数据库成功！！====>"+flag);
		
		return flag;
	}


	@Override
	public List<DocInformation> getFileListByBusinessId(String id) {
		return docInformationMapper.getFileListByBusinessId(id);
	} 
	
	@Override
	public DocInformation selectByPrimaryKey(String id) {
		return docInformationMapper.selectByPrimaryKey(id);
	} 
	
	@Override
	public boolean deleteByPrimaryKey(String id){
		return docInformationMapper.deleteByPrimaryKey(id);
	}
	
	
	
	
	
}
